package com.xbzl.cly_demo.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xbzl.cly_demo.dto.UsersDTO;
import com.xbzl.cly_demo.dto.UsersLoginDTO;
import com.xbzl.cly_demo.entity.Users;
import com.xbzl.cly_demo.exception.AccountNotFoundException;
import com.xbzl.cly_demo.exception.PasswordErrorException;
import com.xbzl.cly_demo.properties.JwtProperties;
import com.xbzl.cly_demo.result.Result;
import com.xbzl.cly_demo.service.UsersService;
import com.xbzl.cly_demo.mapper.UsersMapper;
import com.xbzl.cly_demo.utils.JwtUtil;
import com.xbzl.cly_demo.vo.UsersLoginVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
* @author 26586
* @description 针对表【users】的数据库操作Service实现
* @createDate 2025-04-02 14:06:06
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

    @Autowired
    JwtProperties jwtProperties;
    @Override
    public long register(UsersDTO usersDTO) {
        Users user = new Users();
        BeanUtils.copyProperties(usersDTO,user);
        //密码加密
        String password = user.getPassword();
        user.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
        //默认设置为普通用户
        user.setAuthority("0");

        save(user);
        return user.getUserid();
    }

    @Override
    public Result<UsersLoginVO> login(UsersLoginDTO usersLoginDTO) {
        String username = usersLoginDTO.getUsername();
        String password = usersLoginDTO.getPassword();

        Users user = query().eq("username", username).one();
        if (user == null){
            throw new AccountNotFoundException("不存在此用户");
        }
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(user.getPassword())){
            throw new PasswordErrorException("密码错误");
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        //存入用户id 和 权限
        claims.put("userId",user.getUserid());
        claims.put("authority",user.getAuthority());
        String token = JwtUtil.createJWT(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtl(),
                claims);

        UsersLoginVO usersLoginVO = new UsersLoginVO();
        BeanUtils.copyProperties(user,usersLoginVO);
        usersLoginVO.setToken(token);

        return Result.success(usersLoginVO);
    }
}




